package com.zzzzzz.content.topic;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Locale;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.zzzzzz.account.signin.NoSuchOnlineUserException;
import com.zzzzzz.account.signin.OnlineService;
import com.zzzzzz.common.message.Message;
import com.zzzzzz.common.message.MessageIcon;
import com.zzzzzz.common.page.PageStart;
import com.zzzzzz.content.KindEditorUploadResult;
import com.zzzzzz.content.ContentPictureService;
import com.zzzzzz.content.UserPermissionException;
import com.zzzzzz.content.reply.ReplyService;
import com.zzzzzz.content.reply.ReplyView;
import com.zzzzzz.content.tag.NoSuchTagException;
import com.zzzzzz.content.tag.TagDao;
import com.zzzzzz.core.web.BaseController;

@Controller
public class TopicController extends BaseController {
	@Resource
	private TopicService topicService;
	@Resource
	private TagDao tagDao;
	@Resource
	private OnlineService onlineService;
	@Resource
	private ContentPictureService topicPictureService;
	@Resource
	private ReplyService replyService;
	
	@RequestMapping(value = "/topic/addpic", method = RequestMethod.GET)
	public String addPicPage(@ModelAttribute TopicForm topicForm) {
		return "topic/add_pic";
	}
	
	@RequestMapping(value = "/topic/add", method = RequestMethod.GET)
	public String addPage(@ModelAttribute TopicForm topicForm) {
		return "topic/add";
	}

	/*@RequestMapping(value = "/topic/add", method = RequestMethod.POST)
	public String add(Model model, @Valid TopicForm topicForm, BindingResult bindingResult, RedirectAttributes redirectAttributes, Locale locale) throws NoSuchOnlineUserException, NoSuchTagException {
		if (bindingResult.hasErrors()) {
			return addPage(topicForm);
		}
		
		Long userId = onlineService.findUserId();
		try {
			Long topicId = topicService.add(userId, topicForm);
			return "redirect:/topic/" + topicId;
		} catch (IOException e) {
			redirectAttributes.addFlashAttribute(Message.error(MessageIcon.WARNING + getMessage("message.error.form.content.topic.add.io", locale)));
			return "redirect:/topic/add";
		}
	}*/
	
	@RequestMapping(value = "/topic/uploadimg", method = RequestMethod.POST)
	public @ResponseBody KindEditorUploadResult imageUpload(@RequestParam CommonsMultipartFile imgFile, HttpServletRequest request) {
		try {
			String fileName = topicPictureService.saveArticlePicture(imgFile);
			return new KindEditorUploadResult(0, request.getContextPath() + "/img/" + fileName);
		} catch (IOException e) {
			return new KindEditorUploadResult(1, "上传文件失败。");
		}
	}
	
	/*@RequestMapping(value="/topic/del/{id}", method=RequestMethod.DELETE)
	public String deleteTopic(@PathVariable Long id, Model model, HttpServletRequest request) throws Exception {
		Long userId = onlineService.findUserId();
		topicService.del(id, userId);
		return "redirect:/";
	}

	@RequestMapping(value="/topic/edit/{topicId}", method=RequestMethod.GET)
	public String editPage(@PathVariable Long topicId, @ModelAttribute TopicForm topicForm, Model model) throws NoSuchTopicException, NoSuchOnlineUserException, UserPermissionException, NoSuchTagException {
		Topic topic = topicService.findById(topicId);
		
		Long userId = onlineService.findUserId();
		if(topic.getUserId() != userId) {
			throw new UserPermissionException();
		}
		
		topicForm.updateTopicForm(topic);
		
		model.addAttribute("topicId", topicId);
		model.addAttribute("picId", topic.getPicId());
		
		return "topic/edit";
	}
	
	@RequestMapping(value = "/topic/edit/{topicId}", method=RequestMethod.POST)
	public String edit(@PathVariable Long topicId, @Valid TopicForm topicForm, Model model, BindingResult result, RedirectAttributes redirectAttributes, Locale locale) throws NoSuchOnlineUserException, NoSuchTagException {
		Long userId = onlineService.findUserId();
		try {
			topicService.edit(userId, topicId, topicForm);
			redirectAttributes.addFlashAttribute(Message.success(MessageIcon.OK + getMessage("message.success.form.edit.submit", locale)));
			return "redirect:/topic/" + topicId;
		} catch (IOException e) {
			redirectAttributes.addFlashAttribute(Message.error(MessageIcon.WARNING + getMessage("message.error.form.content.topic.add.io", locale)));
			return "redirect:/topic/edit" + topicId;
		}
	}

	@RequestMapping(value="/topicv/{id}", method=RequestMethod.GET)
	public String viewPage(@PathVariable Long id, 
			@RequestParam(value = "start", defaultValue = "0", required = false) Integer start,
			HttpServletRequest request, Model model) throws Exception {
		TopicView topicView = topicService.findTopicViewById(id);
		if(topicView != null){
			topicService.plusLooks(id);
		}
		model.addAttribute("topicView", topicView);
		
		String replyListUrlEnd = "#replySpan";
		
		List<ReplyView> replyViewList = replyService.findByTopicId(id, start, PageStart.DEFAULT_OFFSET);
		Long replyViewListCount = replyService.findByTopicIdCount(id);
		PageStart replyViewListPageBar = new PageStart(start, PageStart.DEFAULT_OFFSET, replyViewListCount, "/topic/"+id, replyListUrlEnd);
		
		model.addAttribute("replyViewList", replyViewList);
		model.addAttribute("replyViewListCount", replyViewListCount);
		model.addAttribute("replyViewListPageBar", replyViewListPageBar.getPageBar());
		
		model.addAttribute("backUrl", URLEncoder.encode("/topic/"+id+replyListUrlEnd, "UTF-8"));
		
		return "topic/view";
	}
	
	@RequestMapping(value="/topic/{id}", method=RequestMethod.GET)
	public String view(@PathVariable Long id, @RequestParam(value = "start", defaultValue = "0", required = false) Integer start, HttpServletRequest request, Model model) throws Exception {
		TopicView topicView = topicService.findTopicViewById(id);
		if(topicView != null){
			topicService.plusLooks(id);
		}
		model.addAttribute("topicView", topicView);
		
		String replyListUrlEnd = "#replySpan";
		
		List<ReplyView> replyViewList = replyService.findByTopicId(id, start, PageStart.DEFAULT_OFFSET);
		Long replyViewListCount = replyService.findByTopicIdCount(id);
		PageStart replyViewListPageBar = new PageStart(start, PageStart.DEFAULT_OFFSET, replyViewListCount, "/topic/"+id, replyListUrlEnd);
		
		model.addAttribute("replyViewList", replyViewList);
		model.addAttribute("replyViewListCount", replyViewListCount);
		model.addAttribute("replyViewListPageBar", replyViewListPageBar.getPageBar());
		
		model.addAttribute("backUrl", URLEncoder.encode("/topic/"+id+replyListUrlEnd, "UTF-8"));
		
		return "topic/view";
	}

	@RequestMapping(value = "/aaaa", method = RequestMethod.GET)
	public String topicList(@RequestParam(value = "start", defaultValue = "0", required = false) Integer start, HttpServletRequest request, Model model) throws NoSuchTagException {
		List<TopicListView> topicList = topicService.findTopicListView("add_dt desc", start, PageStart.DEFAULT_OFFSET);
		Long count = topicService.findTopicListViewCount();
		PageStart pageStart = new PageStart(start, PageStart.DEFAULT_OFFSET, count, "/");
		
		model.addAttribute("list", topicList);
		model.addAttribute("count", count);
		model.addAttribute("pageBar", pageStart.getPageBar());
		
		return "topic/list";
	}
	
	//@RequestMapping(value = "/tag/{tagName}", method = RequestMethod.GET)
	public String topicList(@PathVariable String tagName, @RequestParam(value = "start", defaultValue = "0", required = false) Integer start, HttpServletRequest request, Model model) throws NoSuchTagException {
		Integer tagId = tagDao.findIdByName(tagName);
		
		List<TopicListView> topicList = topicService.findTopicListViewByTagId(tagId, "add_dt desc", start, PageStart.DEFAULT_OFFSET);
		Long count = topicService.findTopicListViewByTagIdCount(tagId);
		PageStart pageStart = new PageStart(start, PageStart.DEFAULT_OFFSET, count, "/tag/"+tagName);
		
		model.addAttribute("list", topicList);
		model.addAttribute("count", count);
		model.addAttribute("pageBar", pageStart.getPageBar());
		
		return "topic/list";
	}
	
	@RequestMapping(value = "/topic/like/{topicId}", method = RequestMethod.GET)
	public @ResponseBody Integer like(@PathVariable Long topicId) throws NoSuchOnlineUserException {
		Long userId = onlineService.findUserId();
		return topicService.like(topicId, userId);
	}
	
	@RequestMapping(value = "/topic/unfeel/{topicId}", method = RequestMethod.GET)
	public @ResponseBody Integer feelNoLike(@PathVariable Long topicId) throws NoSuchOnlineUserException {
		Long userId = onlineService.findUserId();
		return topicService.unFeel(topicId, userId);
	}*/
}
